package com.jic.member.service.eventHandler.impl.consume;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.tuple.Tuple;
import com.jic.member.entity.model.EventListenerContent;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.function.Predicate;

/**
 * description: RedEnvelopeVerificationHandler
 * date: 2020/6/8 11:41
 * 红包核销
 * admin 参数[{"eventName":"优惠券核销","eventRangeTime":{"f":1591689820000,"s":1593689820000},"promCode":"000001","verificationChannels":"IOS"}]
 * h5 参数 {"eventCode":"redEnvelope_verification","eventTime":1591689920000,"eventType":1,"thirdUserId":"1","param":{"promCode":"000001","verificationChannels":"IOS"}}
 * author: wangys
 * version: 1.0
 */
@Component
public class RedEnvelopeVerificationHandler extends ConsumeEventHandlerTemplate {
    @Override
    public String getEventCode() {
        return "redEnvelope_verification";
    }

    /**
     * 前置参数校验
     * @return
     */
    @Override
    public Predicate<JSONObject> preValidateParam() {
        return (t) -> {
            return t!= null && StringUtils.isNotBlank(t.getString("promCode")) && StringUtils.isNotBlank(t.getString("verificationChannels"));
        };
    }

    @Override
    public Tuple<Boolean, String> validateParam(EventListenerContent content, Long branchNodeId) {
        Tuple<Boolean, String> match = new Tuple<>();
        match.setF(true);
        JSONArray jsonArray = parseNodeVariable.apply(content, branchNodeId);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject param = (JSONObject)jsonArray.get(i);
            String promCode = param.getString("promCode");
            if(!promCode.equals(content.getParam().getString("promCode"))){
                match.setF(false);
                match.setS("红包活动不匹配");
                break;
            }

            String verificationChannels = param.getString("verificationChannels");
            if(verificationChannels != null && !verificationChannels.equals(content.getParam().getString("verificationChannels"))){
                match.setF(false);
                match.setS("核销渠道不匹配");
                break;
            }
        }
        return match;
    }
}
